package juc.day01;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 多线程之间按顺序调用，实现A->B->C
 * 三个线程启动，要求如下：
 * AA打印5次，BB打印10次，CC打印15次；接着
 * AA打印5次，BB打印10次，CC打印15次;
 * ......来10轮
 */
public class T03 {
    public static void main(String[] args) {
        ShareDataOne3 shareDataOne3 = new ShareDataOne3();
        new Thread(()->{
            for (int i=1;i<=10;i++){
                shareDataOne3.print5(i);
            }
        },"AA").start();
        new Thread(()->{
            for (int i=1;i<=10;i++){
                shareDataOne3.print10(i);
            }
        },"BB").start();
        new Thread(()->{
            for (int i=1;i<=10;i++){
                shareDataOne3.print15(i);
            }
        },"CC").start();
    }
}

class ShareDataOne3{
    private Lock lock = new ReentrantLock();
    private int num = 1;    //1:AA 2:BB 3:CC
    private Condition conditionA = lock.newCondition();
    private Condition conditionB = lock.newCondition();
    private Condition conditionC = lock.newCondition();

    public void print5(int j){
        lock.lock();
        try{
            // 判断
            while (num != 1){
                conditionA.await();
            }
            // 干活
            for(int i=1;i<=5;i++){
                System.out.println("轮次："+j+";"+Thread.currentThread().getName()+":"+i);
            }
            // 通知
            num = 2;
            conditionB.signal();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }

    public void print10(int j){
        lock.lock();
        try{
            // 判断
            while (num != 2){
                conditionB.await();
            }
            // 干活
            for(int i=1;i<=10;i++){
                System.out.println("轮次："+j+";"+Thread.currentThread().getName()+":"+i);
            }
            // 通知
            num = 3;
            conditionC.signal();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }

    public void print15(int j){
        lock.lock();
        try{
            // 判断
            while (num != 3){
                conditionC.await();
            }
            // 干活
            for(int i=1;i<=15;i++){
                System.out.println("轮次："+j+";"+Thread.currentThread().getName()+":"+i);
            }
            // 通知
            num = 1;
            conditionA.signal();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }
}
